import {common_getQiniuToken} from '@/api/qiniuToken/qiniuToken'
import qiniuUploader from "../utils/qiniuUploader";
import {qiniuSpace} from "./myConfig";
import permision from "./appPermission.js";

// 获取七牛上传token 并 初始化七牛相关参数
let qiniuToken = ''

export async function getQiniuToken() {
  return new Promise((resolve, reject) => {
    common_getQiniuToken().then((res) => {
      qiniuToken = res.data.token
      let options = {
        region: "ECN", // 华东区
        uptoken: res.data.token
      };
      qiniuUploader.init(options);
      resolve(res);
    }).catch((err) => {
      console.log('err    is:' + JSON.stringify(err));
    });
  });

}

// 微信拍照并获取本地 路径
export function getLocalityImage() {
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
      count: 1,
      success(res) {
        let tempFilePaths = res.tempFilePaths[0];
        resolve(tempFilePaths);
      },
      fail(err) {
        console.log('报错===>>>>' + JSON.stringify(err))
        reject(err);
      }
    });
  });
}

// 拍照并七牛上传图片
export function chooseImage(count) {
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
      count: count,
      success: res => {
        const tempFilePaths = res.tempFilePaths;
        let image_array = [];
        let imgs = tempFilePaths.map((value, index) => {
          return {
            name: index,
            uri: value
          }
        })
        for (let i = 0; i < tempFilePaths.length; i++) {
          let suffix = tempFilePaths[i].substr(tempFilePaths[i].length - 4, tempFilePaths[i].length)
          uni.uploadFile({
            url: 'http://upload.qiniup.com/',
            filePath: tempFilePaths[i],
            name: 'file',
            header: {
              'content-type': 'multipart/form-data'
            },
            formData: {
              key: `cbd${i}twoapp${new Date().getTime()}cbd${i}twoapp${suffix}`,
              token: qiniuToken,
              'type': 'image',
            },
            success: result => {
              console.log(result)
              image_array.push(getImgRealUrl(JSON.parse(result.data).key));
              if (tempFilePaths.length == image_array.length) {
                resolve({image_array: image_array})
              }
            },
            fail(err) {
              console.error("微信上传图片err: " + JSON.stringify(err));
              uni.showToast({
                title: '上传图片失败',
                icon: 'none',
              })
            }
          });
        }
      },
      fail(err) {
        let temp_system_info = uni.getStorageSync('system_info').system;
        let system_info = temp_system_info.substr(0,2);
        if(err.code === 2){
          test_authority().then();
        }
        console.error("微信上传图片err: " + JSON.stringify(err));
      }
    });
  });
}

/**
 * 拍照并七牛上传视频
 */
export function chooseVideo() {
  return new Promise((resolve, reject) => {
    uni.chooseVideo({
      count: 1,
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res)
        let tempFilePath = res.tempFilePath;
        let suffix = res.tempFilePath.substr(tempFilePath.length - 4, tempFilePath.length)
        if (suffix === '.wmv') {
          uni.showToast({
            title: '不支持此格式的视频，上传失败',
            icon: 'none'
          })
        } else {
          uni.showLoading({
            title: '视频上传中'
          });
          uni.uploadFile({
            url: 'http://upload.qiniup.com/',
            filePath: tempFilePath,
            name: 'file',
            formData: {
              key: new Date().getTime() + suffix,
              token: qiniuToken,
              'type': 'video',
            },
            success: result => {
				console.log(result)
              uni.hideLoading();
              let video = getImgRealUrl(JSON.parse(result.data).key)
			  console.log(video)
              resolve(video)
            },
            fail(err) {
              uni.showToast({
                title: '上传视频失败',
                icon: 'none',
              })
            }
          })
        }
      },
      fail(err) {
        let temp_system_info = uni.getStorageSync('system_info').system;
        let system_info = temp_system_info.substr(0,2);
        if(err.code === 2){
          console.log(1111)
          test_authority().then();
        }
        console.error("微信上传图片err: " + JSON.stringify(err));
      }
    });
  });
}

/**
 * 人性化时间处理 传入时间戳
 */
export function formatTime(timestamp) {
  var mistiming = Math.round(new Date() / 1000) - timestamp;
  var postfix = mistiming > 0 ? '前' : '后'
  mistiming = Math.abs(mistiming)
  var arrr = ['年', '个月', '星期', '天', '小时', '分钟', '秒'];
  var arrn = [31536000, 2592000, 604800, 86400, 3600, 60, 1];

  for (var i = 0; i < 7; i++) {
    var inm = Math.floor(mistiming / arrn[i])
    if (inm != 0) {
      return inm + arrr[i] + postfix
    }
  }
}

/**
 * 数字转换  例如1123456转换为112.3w
 */
export function numSwitch(num) {
  num = num.toString()
  if (num.length < 4) {
    return num
  }
  let res_str, one, two;
  switch (num.length) {
    case 4:
      one = num.substr(0, 1);
      two = num.substr(1, 2);
      res_str = `${one}.${two}k`;
      break;
    case 5:
      one = num.substr(0, 1);
      two = num.substr(1, 2);
      res_str = `${one}.${two}w`;
      break;
    case 6:
      one = num.substr(0, 2);
      two = num.substr(2, 1);
      res_str = `${one}.${two}w`;
      break;
    case 7:
      one = num.substr(0, 3);
      two = num.substr(3, 1);
      res_str = `${one}.${two}w`;
      break;
    default:
      res_str = num;
      break;
  }
  return res_str;
}

export async function test_authority(){
  let platform_info = uni.getStorageSync('system_info').platform
  let system_info = uni.getStorageSync('system_info').system;
  if(platform_info == 'android'){
    let text_authority_camera = await permision.requestAndroidPermission("android.permission.CAMERA")
    let text_authority_read_external_storage = await permision.requestAndroidPermission("android.permission.READ_EXTERNAL_STORAGE")
    let text_authority_write_external_storage = await permision.requestAndroidPermission("android.permission.WRITE_EXTERNAL_STORAGE")
    if(!text_authority_camera || !text_authority_read_external_storage || !text_authority_write_external_storage){
      uni.showModal({
        title: '提示',
        content: '您已拒绝本次申请的权限，请在设置中开启',
        success: function (res){
          if (res.confirm) {
            // permision.gotoAppPermissionSetting()
          }
          if(res.cancel){
          }
        }
      })
    }
  }else {
    permision.judgeIosPermission("camera")
    permision.judgeIosPermission("photoLibrary")
    permision.judgeIosPermission("record")
  }
}



/**  防抖 非立即执行 不可以使用箭头函数
 * @author DQD
 * @param {function} fn
 * @param {number} delay 防抖延时默认 500毫秒
 * @param {boolean} isImmediate
 *
 * @return 执行的需要发抖的函数
 */
export const debounce = (fn, delay = 500, isImmediate = true) => {
  let timer;
  return function () {
    if (isImmediate) {
      if (timer) {
        clearTimeout(timer)
      } else {
        fn.apply(this, arguments);
      }
      timer = setTimeout(() => {
        timer = null;
      }, delay);
    } else {
      if (timer) clearTimeout(timer);
      timer = setTimeout(() => {
        timer = null;
        fn.apply(this, arguments);
      }, delay);
    }
  }
}

export function uniNavigateTo(url_opt = {url: '', query: {}, ...other}) {
  if (typeof url_opt.url === 'string' &&  !url_opt.url) {
    return
  }
  let url = ''
  if (url_opt.url) {
    url = `${url_opt.url.substr(0, 1) === '/' ? '' : '/'}${url_opt.url}`;
  }

  if (url_opt.query && typeof url_opt.query === 'object') {
    let query_arr = [];
    for (let queryKey in url_opt.query) {
      query_arr.push(`${queryKey}=${url_opt.query[queryKey]}`);
    }
    url += `?${query_arr.join('&')}`;
  }
  let query_other = url_opt
  delete query_other.url
  delete query_other.query
  uni.navigateTo({
    url,
    ...query_other
  })
}

// 转换真实地址
export function getImgRealUrl(key) {
  /**
   * 后端修改目前不需要测试七牛域名全部更换为正式七牛域名
   *
   * 测试七牛域名:http://saas.baoguoer.com/
   *
   * @author: 抠鼻屎的大熊i
   * @author: 2020年11月6日16:21:57
   * */
  return qiniuSpace + key;

  /**
   * 正式测试目前还需要区分 等待后端进行修改
   * */
  // return 'http://saas.baoguoer.com/' + key;
}

export default {
  getQiniuToken,
  numSwitch,
  chooseImage,
  chooseVideo,
  debounce,
  formatTime,
  test_authority
};
